package cn.xyinping.basic.controller;

import cn.xyinping.basic.util.AjaxResult;
import cn.xyinping.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author 27266
 * @desrciption fastDfs接口
 * @date 2021/10/27
 */
@RestController
@RequestMapping("/fastDfs")
public class FastdfsController {
    /**
     * 上传
     * @param file
     * @return
     * 上传文件用RequestPart
     */
    @PostMapping
    public AjaxResult upload(@RequestPart (required = true, value = "file")MultipartFile file){
        try {
            // 获取图片名称
            String filename = file.getOriginalFilename(); // sdsd.dasd.dds.jpg
            // 截取图片后缀
            String extName = filename.substring(filename.lastIndexOf(".") + 1); // jpg
            // 上传
            String path = FastDfsUtil.upload(file.getBytes(), extName);// /group1/lksadjf./sadf.jpg
            // 给前端返回上传路径
            return AjaxResult.me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统错误");
        }
    }

    /**
     * 删除文件
     * @param path
     * @return
     * 删除文件用 RequestParam
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam String path){
        try {
            String pathTmp = path.substring(1); // group1/xxx/yyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1); //xxx/yyy
            FastDfsUtil.delete(groupName, remotePath); // FastDfsUtil中提供只能传 组名，图片名
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统错误");
        }
    }

}
